package com.itwlj.task;

import com.itwlj.constant.StatusConstant;
import com.itwlj.entity.Order;
import com.itwlj.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    @Value("${mall.countdown}")
    private Integer countdown;

    /**
     * 处理已收货订单的方法
     */
    @Scheduled(cron = "0 0 0 * * ?") // 每天的 00:00 触发一次
    public void processReceivedOrder(){
        log.info("定时已收货订单：{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().minusDays(7);

        // select * from orders where status = ? and order_time < (当前时间 - xx天)
        List<Order> ordersList = orderMapper.getByStatusAndCreateTimeLT(StatusConstant.ORDER_RECEIVED, time);

        if(ordersList != null && ordersList.size() > 0){
            for (Order order : ordersList) {
                order.setPayResult(StatusConstant.ORDER_COMPLETED);
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void processTimeoutOrder(){
        log.info("处理超时订单：{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().minusMinutes(countdown/1000/60);

        List<Order> ordersList = orderMapper.getByStatusAndCreateTimeLT(StatusConstant.ORDER_UNPAID, time);

        if(ordersList != null && ordersList.size() > 0){
            for (Order order : ordersList) {
                order.setOrderState(StatusConstant.ORDER_CLOSE);
                order.setPayResult(StatusConstant.ORDER_PAYMENT_FAILED);
                order.setCloseTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }
}
